//
//  ZMSpeedy.m
//  FM_Project
//
//  Created by chenzm on 2019/8/7.
//  Copyright © 2019 DL. All rights reserved.
//

#import "ZMSpeedy.h"
#import <CoreLocation/CLLocationManager.h>

@implementation ZMSpeedy

+(id)zm_changeControl:(UIView *)anyControl cornerRadius:(NSInteger)radius borderWidth:(NSInteger)width borderColor:(UIColor *)borderColor mask:(BOOL)can{
    CALayer *icon_layer=[anyControl layer];
    [icon_layer setCornerRadius:radius];
    [icon_layer setBorderWidth:width];
    [icon_layer setBorderColor:[borderColor CGColor]];
    [icon_layer setMasksToBounds:can];
    return anyControl;
}

//添加边框
+ (void)zm_setBorderWithView:(UIView *)view top:(BOOL)top left:(BOOL)left bottom:(BOOL)bottom right:(BOOL)right borderColor:(UIColor *)color borderWidth:(CGFloat)width {
    if (top) {
        CALayer *layer = [CALayer layer];
        layer.frame = CGRectMake(0, 0, view.frame.size.width, width);
        layer.backgroundColor = color.CGColor;
        [view.layer addSublayer:layer];
    }
    if (left) {
        CALayer *layer = [CALayer layer];
        layer.frame = CGRectMake(0, 0, width, view.frame.size.height);
        layer.backgroundColor = color.CGColor;
        [view.layer addSublayer:layer];
    }
    if (bottom) {
        CALayer *layer = [CALayer layer];
        layer.frame = CGRectMake(0, view.frame.size.height - width, view.frame.size.width, width);
        layer.backgroundColor = color.CGColor;
        [view.layer addSublayer:layer];
    }
    if (right) {
        CALayer *layer = [CALayer layer];
        layer.frame = CGRectMake(view.frame.size.width - width, 0, width, view.frame.size.height);
        layer.backgroundColor = color.CGColor;
        [view.layer addSublayer:layer];
    }
}

/**
 贝塞尔曲线设置圆角【UIRectCornerTopLeft、Right】
 
 @param anyControl 控件
 @param corners 圆角位置
 @param radius 圆角尺寸
 */
+ (void)zm_changeControl:(UIView *)anyControl bezierCorner:(UIRectCorner)corners radius:(CGSize)radius{
    CALayer *icon_layer=[anyControl layer];
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:icon_layer.bounds byRoundingCorners:corners cornerRadii:radius];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = icon_layer.bounds;
    maskLayer.path = maskPath.CGPath;
    icon_layer.mask = maskLayer;
}


/**
 选取部分数据变色（label）
 
 @param label label
 @param arrray 变色数组
 @param color 变色颜色
 @return label
 */
+(id)zm_setSomeOneChangeColor:(UILabel *)label SetSelectArray:(NSArray *)arrray SetChangeColor:(UIColor *)color
{
    if (label.text.length == 0) {
        return 0;
    }
    int i;
    NSMutableAttributedString *attributeString  = [[NSMutableAttributedString alloc]initWithString:label.text];
    for (i = 0; i < label.text.length; i ++) {
        NSString *a = [label.text substringWithRange:NSMakeRange(i, 1)];
        NSArray *number = arrray;
        if ([number containsObject:a]) {
            [attributeString setAttributes:@{NSForegroundColorAttributeName:color} range:NSMakeRange(i, 1)];
        }
    }
    label.attributedText = attributeString;
    return label;
}


// 计算目录大小
+ (CGFloat)folderSizeAtPath:(NSString *)path{
    // 利用NSFileManager实现对文件的管理
    NSFileManager *manager = [NSFileManager defaultManager];
    CGFloat size = 0;
    if ([manager fileExistsAtPath:path]) {
        // 获取该目录下的文件，计算其大小
        NSArray *childrenFile = [manager subpathsAtPath:path];
        for (NSString *fileName in childrenFile) {
            NSString *absolutePath = [path stringByAppendingPathComponent:fileName];
            size += [manager attributesOfItemAtPath:absolutePath error:nil].fileSize;
        }
        // 将大小转化为M
        return size / 1024.0 / 1024.0;
    }
    return 0;
}
// 根据路径删除文件
+(void)cleanCaches:(NSString *)path{
    // 利用NSFileManager实现对文件的管理
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:path]) {
        // 获取该路径下面的文件名
        NSArray *childrenFiles = [fileManager subpathsAtPath:path];
        for (NSString *fileName in childrenFiles) {
            // 拼接路径
            NSString *absolutePath = [path stringByAppendingPathComponent:fileName];
            // 将文件删除
            [fileManager removeItemAtPath:absolutePath error:nil];
        }
    }
}


#pragma mark - 随机数
+ (NSInteger)zm_GetRandomNumber:(NSInteger)StarNum to:(NSInteger)endNum
{
    return (NSInteger)(StarNum + (arc4random() % ((StarNum - endNum )+ 1)));
}


#pragma mark -  根据传入字体大小计算字体宽高

+ (CGSize)zm_calcuStrSize:(NSString *)text font: (UIFont *)font maxW:(CGFloat)maxW{
    CGSize textMaxSize = CGSizeMake(maxW, MAXFLOAT);
    CGSize textSize = [text boundingRectWithSize:textMaxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font} context:nil].size;
    return textSize;
}


+ (CGSize)zm_calcuAttStrSize:(NSAttributedString *)string maxW:(CGFloat)maxW{
    if (string.length == 0) {
        return CGSizeMake(0, 0);
    }
    CGSize size  = [string boundingRectWithSize:CGSizeMake(maxW, MAXFLOAT) options: NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading  context:nil].size;
    return size;
}

#pragma mark - 首行缩进
+ (void)zm_setUpLabel:(UILabel *)label Content:(NSString *)content IndentationFortheFirstLineWith:(CGFloat)emptylen
{
    NSMutableParagraphStyle *paraStyle01 = [[NSMutableParagraphStyle alloc] init];
    paraStyle01.firstLineHeadIndent = emptylen;//首行缩进
    NSAttributedString *attrText = [[NSAttributedString alloc] initWithString:content attributes:@{NSParagraphStyleAttributeName:paraStyle01}];
    
    label.attributedText = attrText;
}

#pragma mark - 设置圆角
+ (void)zm_setUpBezierPathCircularLayerWithControl:(UIButton *)control size:(CGSize)size;
{
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:control.bounds byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight | UIRectCornerTopLeft |UIRectCornerTopRight cornerRadii:size];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = control.bounds;
    maskLayer.path = maskPath.CGPath;
    control.layer.mask = maskLayer;
}

#pragma mark - 字符串加星处理
+ (NSString *)zm_encryptMsg:(NSString *)content
                 startIndex:(NSInteger)findex
{
    if (findex <= 0) {
        findex = 2;
    }else if (findex + findex > content.length) {
        findex --;
    }
    return [NSString stringWithFormat:@"%@***%@",[content substringToIndex:findex],[content substringFromIndex:content.length - findex]];
}


/**
 格式化文本显示
 @param hisStr 要格式化的文本
 @param str 添加的内容
 @param num 添加的间隔
 @return 返回格式化的文本
 */
+(NSString *)zmFormateStr:(NSString *)hisStr addStr:(NSString *)str intervalNum:(NSInteger)num{
    NSMutableAttributedString *mStr = [[NSMutableAttributedString alloc]init];
    if (hisStr.length > num){
        for (NSInteger i = 0; i < hisStr.length ; i ++) {
            if (i%num == 0&&i>0) {
                [mStr yy_appendString:str];
            }
            [mStr yy_appendString:[hisStr substringWithRange:NSMakeRange(i, 1)]];
        }
    }
    return mStr.string;
}

+(NSString *)UIImageToBase64Str:(UIImage *) image
{
    NSData *data = UIImageJPEGRepresentation(image, 1.0f);
    NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    return encodedImageStr;
}

#pragma mark - base64图片转编码
+(UIImage *)Base64StrToUIImage:(NSString *)_encodedImageStr
{
    NSData *_decodedImageData = [[NSData alloc] initWithBase64EncodedString:_encodedImageStr options:NSDataBase64DecodingIgnoreUnknownCharacters];
    UIImage *_decodedImage = [UIImage imageWithData:_decodedImageData];
    return _decodedImage;
}

+ (void)zm_SetUpAlterWithView:(UIViewController *)vc Message:(NSString *)message Sure:(dispatch_block_t)sureBlock Cancel:(dispatch_block_t)cancelBlock
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    //取消
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action){
        !cancelBlock ? : cancelBlock();
    }];
    //确定
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
        !sureBlock ? : sureBlock();
    }];
    [alertController addAction:cancelAction];
    [alertController addAction:okAction];
    
    [vc presentViewController:alertController animated:YES completion:nil];
}

#pragma mark - 触动
+ (void)zm_callFeedback
{
    if (@available(iOS 10.0, *)) {
        UIImpactFeedbackGenerator *generator = [[UIImpactFeedbackGenerator alloc] initWithStyle: UIImpactFeedbackStyleHeavy];
        [generator prepare];
        [generator impactOccurred];
    }
    
}


#pragma mark - 获取当前屏幕显示的VC
+ (UIViewController *)zm_getCurrentVC
{
    UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
    
    UIViewController *currentVC = [self getCurrentVCFrom:rootViewController];
    
    return currentVC;
}

+ (UIViewController *)getCurrentVCFrom:(UIViewController *)rootVC
{
    UIViewController *currentVC;
    
    if([rootVC presentedViewController]) {
        // 视图是被presented出来的
        rootVC = [rootVC presentedViewController];
    }
    if([rootVC isKindOfClass:[UITabBarController class]]) {
        // 根视图为UITabBarController
        currentVC = [self getCurrentVCFrom:[(UITabBarController *)rootVC selectedViewController]];
        
    }else if([rootVC isKindOfClass:[UINavigationController class]]){
        // 根视图为UINavigationController
        currentVC = [self getCurrentVCFrom:[(UINavigationController *)rootVC visibleViewController]];
        
    }else{
        // 根视图为非导航类
        currentVC = rootVC;
    }
    return currentVC;
}

#pragma mark - 本地缓存数据处理
/**
 获取本地缓存数据
 
 @param key 键值
 @return 返回值
 */
+(id)getLocalObj:(NSString *)key{
    id obj = [kUserDefaults objectForKey:key];
    if (obj) {
        return obj;
    }
    return nil;
}

/**
 缓存数据
 
 @param obj 需要缓存的值
 @param key 键值
 */
+(void)saveLocalObj:(id)obj key:(NSString *)key{
    [kUserDefaults setObject:obj forKey:key];
    [kUserDefaults synchronize];
}

/**
 删除本地缓存
 
 @param key 键值
 */
+(void)delateLocalObj:(NSString *)key{
    [kUserDefaults removeObjectForKey:key];
    [kUserDefaults synchronize];
}



/// 将View转化为图片
+ (UIImage*)getImageFromView:(UIView*)fview{
    UIGraphicsBeginImageContextWithOptions(fview.bounds.size, NO, 0.0);
    [fview.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndPDFContext();
    return newImage;
}

// 获取项目图片资源
+ (UIImage *)imageWithFile:(NSString *)url {
    NSBundle *bundle = [NSBundle mainBundle];
    NSString *resourcePath = [bundle resourcePath];
    UIImage *image = [UIImage imageWithContentsOfFile:[resourcePath stringByAppendingPathComponent:url]];
    return image;
}

/**
 *  图片增加水印图片
 *
 *  @param superImage 需要增加水印的图片
 *  @param subImage   水印图片
 *  @param posRect    水印的位置 和 水印的大小
 *
 *  @return 加水印后的新图片
 */
+ (UIImage *)addImageToSuperImage:(UIImage *)superImage withSubImage:(UIImage *)subImage andSubImagePosition:(CGRect)posRect{
    
    UIGraphicsBeginImageContext(superImage.size);
    [superImage drawInRect:CGRectMake(0, 0, superImage.size.width, superImage.size.height)];
    //四个参数为水印图片的位置
    
    [subImage drawInRect:posRect];
    UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return resultingImage;
}

/**
 修改图片尺寸
 @param size 需要修改图片大小
 @param hisImage 需要修改压缩的图片
 @return 修改够的图片
 */
+ (UIImage *)imageByResizeToSize:(CGSize)size image:(UIImage *)hisImage{
    if (size.width <= 0 || size.height <= 0) return nil;
    UIGraphicsBeginImageContextWithOptions(size, NO, hisImage.scale);
    [hisImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}


/// 质量大小压缩相结合【返回image】
/// @param image 要压缩的图片
/// @param maxLength 压缩的最大质量
+ (UIImage *)zm_compressSizeAndQualityImage:(UIImage *)image toByte:(NSUInteger)maxLength {
    CGFloat compressQuality = 1;
    NSData *data = UIImageJPEGRepresentation(image, compressQuality);
    if (data.length < maxLength) {
    //质量小于压缩大小
        return image;
    }
   /*压缩质量*/
    //指定大小压缩比例
    compressQuality = (CGFloat)maxLength/(CGFloat)data.length;
    data = UIImageJPEGRepresentation(image, compressQuality);
    UIImage *resultImage = [UIImage imageWithData:data];
    if (data.length < maxLength) {
    //质量小于压缩大小
        return resultImage;
    }
   /*压缩大小*/
    NSUInteger lastDataLenth = 0;
    while (data.length > maxLength && data.length != lastDataLenth) {
        lastDataLenth = data.length;
        //计算压缩比例
        CGFloat compressSize = (CGFloat) maxLength/(CGFloat)data.length;
        CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(compressSize)), (NSUInteger)(resultImage.size.height * sqrtf(compressSize)));
        UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
        [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
        resultImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();

        data = UIImageJPEGRepresentation(resultImage, 1);
    }
    return resultImage;

}

/// 质量大小压缩相结合【返回Data】
/// @param image 要压缩的图片
/// @param maxLength 压缩的最大质量
+(NSData *)zm_getImgData:(UIImage *)image toByte:(NSUInteger)maxLength{
    CGFloat compressQuality = 1;
    NSData *data = UIImageJPEGRepresentation(image, compressQuality);
     if (data.length < maxLength) {
     //质量小于压缩大小
         return data;
     }
    /*压缩质量*/
     //指定大小压缩比例
     compressQuality = (CGFloat)maxLength/(CGFloat)data.length;
     data = UIImageJPEGRepresentation(image, compressQuality);
    if (data.length < maxLength) {
    //质量小于压缩大小
        return data;
    }
    /*压缩大小*/
    NSUInteger lastDataLenth = 0;
    UIImage *resultImage = [UIImage imageWithData:data];
    while (data.length > maxLength && data.length != lastDataLenth) {
        lastDataLenth = data.length;
        //计算压缩比例
        CGFloat compressSize = (CGFloat) maxLength/(CGFloat)data.length;
        CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(compressSize)), (NSUInteger)(resultImage.size.height * sqrtf(compressSize)));
        UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
        [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
        resultImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        data = UIImageJPEGRepresentation(resultImage, 1);
    }
    return data;
}

/// 将UIImage转换为NSData
+ (NSData*)zm_dataFromImage:(UIImage*)image{
    NSData *data;
    
    if (UIImageJPEGRepresentation(image,1.0)){
        // 判断图片是不是jpeg格式的文件
        data = UIImageJPEGRepresentation(image,1.0);
    }else{
        // 判断图片是不是png格式的文件
        data = UIImagePNGRepresentation(image);
    }
    return data;
}

/// 判断是否开启定位
+(BOOL)zm_judgeIsAppOpensTheLocation{
    if ([CLLocationManager authorizationStatus] ==kCLAuthorizationStatusDenied) {
        //定位不能用
        return NO;
    }else{
        /*
        kCLAuthorizationStatusNotDetermined                  //用户尚未对该应用程序作出选择
        kCLAuthorizationStatusRestricted                     //应用程序的定位权限被限制
        kCLAuthorizationStatusAuthorizedAlways               //一直允许获取定位
        kCLAuthorizationStatusAuthorizedWhenInUse            //在使用时允许获取定位
        kCLAuthorizationStatusAuthorized                     //已废弃，相当于一直允许获取定位
        kCLAuthorizationStatusDenied                         //拒绝获取定位
        */
         return YES;
    }
}







#pragma mark --【时间】转换与计算

/**
 时间戳（LL）转nsdate
 
 @param timeLine 时间戳
 @return 返回日期
 */
+(NSDate *)changeNSDateFromLL:(long long)timeLine{
    NSTimeInterval timeInterval = timeLine;
    NSDate * cmpare = [NSDate dateWithTimeIntervalSince1970:timeInterval];
    return cmpare;
}
/**
 字符串（Str）转nsdate
 
 @param dateStr 字符村
 @return 返回date
 */
+(NSDate *)changeNSDateFromStr:(NSString *)dateStr{
    long long dateLL = [ZMSpeedy changeLLFromString:dateStr format:nil];
    NSDate *date = [ZMSpeedy changeNSDateFromLL:dateLL];
    return date;
}

/**
 NSDate类型转LL类型
 
 @param date 日期
 @return 返回LL类型
 */
+(long long)changeLLFromDate:(NSDate *)date{
    NSString *format = @"yyyy-MM-dd HH:mm:ss";
    NSString *dateStr = [ZMSpeedy changeStrFromDate:date dateFormat:format];
    long long dateLL = [ZMSpeedy changeLLFromString:dateStr format:format];
    return dateLL;
}

/**
 字符串（Str）转换成LL
 
 @param theTime 字符串时间
 @param format 格式,空为默认
 @return 返回时间戳
 */
+(long long)changeLLFromString:(NSString *)theTime format:(NSString *)format{
    //装换为时间戳
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    if (format) {
        [formatter setDateFormat:format];
    }else{
        [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    }
    NSDate* dateTodo = [formatter dateFromString:theTime];
    return [dateTodo timeIntervalSince1970]*1000;
}

/**
 将NSDate转成字符串（Str）
 
 @param date 日期
 @param dateFormat 转化格式
 @return 返回字符串时间
 */
+(NSString *)changeStrFromDate:(NSDate *)date dateFormat:(NSString *)dateFormat{
    NSDateFormatter* fmt = [[NSDateFormatter alloc] init];
    fmt.locale = [NSLocale systemLocale];
    fmt.dateFormat = dateFormat;
    NSString * dateStr = [fmt stringFromDate:date];
    return dateStr;
}

/**
 将LongLong转成字符串（Str）
 
 @param dateLon 日期
 @param dateFormat 转化格式
 @return 返回字符串时间
 */
+(NSString *)changeStrFromLL:(long long)dateLon dateFormat:(NSString *)dateFormat{
    NSDate *date = [ZMSpeedy changeNSDateFromLL:dateLon];
    NSDateFormatter* fmt = [[NSDateFormatter alloc] init];
    fmt.locale = [NSLocale systemLocale];
    fmt.dateFormat = dateFormat;
    NSString * dateStr = [fmt stringFromDate:date];
    return dateStr;
}

/**
 将NSDate时间转成字符串时间(yy年MM月dd日 HH:mm)
 
 @param date 日期
 @return 返回字符串时间
 */
+(NSString *)getYYMMDDHHMMStrTimeFromDate:(NSDate *)date{
    NSDateFormatter* fmt = [[NSDateFormatter alloc] init];
    fmt.locale = [NSLocale systemLocale];
    fmt.dateFormat = @"yy年MM月dd日 HH:mm";
    NSString * dateStr = [fmt stringFromDate:date];
    return dateStr;
}
/**
 将NSDate时间转成字符串时间(MM月dd日 HH:mm)
 
 @param date 日期
 @return 返回字符串时间
 */
+(NSString *)getMMDDHHMMStrTimeFromDate:(NSDate *)date{
    NSDateFormatter* fmt = [[NSDateFormatter alloc] init];
    fmt.locale = [NSLocale systemLocale];
    fmt.dateFormat = @"MM月dd日 HH:mm";
    NSString * dateStr = [fmt stringFromDate:date];
    return dateStr;
}

/**
 根据提供时间计算距离现在多长时间
 
 @param compareDate 提供时间
 @return 返回字符串显示自检
 */
+(NSString *) compareCurrentTime:(NSDate*) compareDate
{
    NSTimeInterval  timeInterval = [compareDate timeIntervalSinceNow];
    timeInterval = -timeInterval;
    long temp = 0;
    NSString *result;
    if (timeInterval < 60) {
        result = [NSString stringWithFormat:@"刚刚"];
    }
    else if((temp = timeInterval/60) <60){
        result = [NSString stringWithFormat:@"%ld分钟前",temp];
    }
    else if((temp = temp/60) <24){
        result = [NSString stringWithFormat:@"%ld小时前",temp];
    }
    else if((temp = temp/24) == 1){
        return  result = @"昨天";
    }
    else if (temp == 2){
        return result = @"前天";
    }else{
        result = [ZMSpeedy changeStrFromDate:compareDate dateFormat:@"yyyy年MM月dd日"];
    }
    return  result;
}


#pragma mark -
#pragma mark - CAKeyframeAnimation动画
/**
 点击缩放动画
 @pragram layer:【添加对象】
 */
+(void)zm_animationClickByScale:(CALayer *)layer{
    //需要实现的帧动画,这里根据自己需求改动
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animation];
    animation.keyPath = @"transform.scale";
    animation.values = @[@1.0,@1.2,@0.8,@1.0];
    animation.duration = 0.3;
    animation.calculationMode = kCAAnimationCubic;
    [layer addAnimation:animation forKey:nil];
}

/**
 点击动画效果
 @pragram layer:【添加对象】
 @pragram type:【格式】 rippleEffect(涟漪)，fade（淡出）,moveIn（移入）,push（推进），reveal（揭开）,cube(立体旋转)
 @pragram subType:【动画方向】fromLeft,fromRight,fromTop，fromBottom
 @pragram duration:持续时间[<0取默认时间1秒]
 @pragram key: 键值
 */
+(void)zm_animationWithLayer:(CALayer *)layer type:(NSString *)type subType:(NSString *)subType duraton:(CFTimeInterval)duration key:(NSString *)key{
    //kCATransitionFromLeft
    CATransition *transition = [CATransition animation];
    //设置动画的持续时间
    duration = duration<0?1:duration;
    [transition setDuration:duration];
    ///动画类型
    [transition setType:type];
    ///动画方向
    [transition setSubtype:subType];
    //动画开始和结束时间的快慢
    [transition setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault]];
    //动画的key
    key = !key?@"":key;
    [layer addAnimation:transition forKey:key];
}

///添加视图动画【慢慢放大】
+(void)zm_showViewByAnimationWithLayer:(CALayer *)layer duraton:(CFTimeInterval)duration{
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    if (duration == 0) {
        animation.duration = 0.3;
    }else{
        animation.duration = duration;
    }
    
    NSMutableArray *values = [NSMutableArray array];
    
    [values addObject:[NSValue valueWithCATransform3D: CATransform3DMakeScale(0.5, 0.5, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D: CATransform3DMakeScale(0.75, 0.75, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D: CATransform3DMakeScale(1.0, 1.0, 1.0)]];
    animation.values = values;
    [layer addAnimation:animation forKey:nil];
}

///添加视图动画【慢慢最大 缩小 还原】
+(void)zm_showViewByAnimation_BMR_WithLayer:(CALayer *)layer duraton:(CFTimeInterval)duration{
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    if (duration == 0) {
        animation.duration = 0.3;
    }else{
        animation.duration = duration;
    }
    
    NSMutableArray *values = [NSMutableArray array];
    [values addObject:[NSValue valueWithCATransform3D: CATransform3DMakeScale(1.0, 1.0, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D: CATransform3DMakeScale(1.1, 1.1, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D: CATransform3DMakeScale(0.85, 0.85, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D: CATransform3DMakeScale(1.0, 1.0, 1.0)]];
    animation.values = values;
    [layer addAnimation:animation forKey:nil];
}

///添加视图动画【自定义】
+(void)zm_showAnimationWithLayer:(CALayer *)layer duraton:(CFTimeInterval)duration scaleA:(CGFloat)scaleA scaleB:(CGFloat)scaleB{
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    if (duration == 0) {
        animation.duration = 0.3;
    }else{
        animation.duration = duration;
    }
    
    NSMutableArray *values = [NSMutableArray array];
    [values addObject:[NSValue valueWithCATransform3D: CATransform3DMakeScale(1.0, 1.0, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D: CATransform3DMakeScale(scaleA, scaleA, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D: CATransform3DMakeScale(scaleB, scaleB, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D: CATransform3DMakeScale(1.0, 1.0, 1.0)]];
    animation.values = values;
    [layer addAnimation:animation forKey:nil];
    
}
///移除页面的动画
+(void)zm_removeViewByAnimationWithView:(UIView *)view duraton:(CFTimeInterval)duration{
    [UIView animateWithDuration:duration
                     animations:^{
                         view.alpha = 0;
                         [view layoutSubviews];
                     } completion:^(BOOL finished) {
                         view.alpha = 1;
                         [view removeFromSuperview];
                     }];
}
#pragma mark -
#pragma mark - 富文本

/**
添加中划线富文本
@param text 文本
@param color 颜色
@param font 字体大小
*/
+(NSMutableAttributedString *)zm_richText_centerLineText:(NSString *)text font:(UIFont *)font color:(UIColor *)color{
    if (!text) {
        text = @" ";
    }
    NSDictionary *attrDic = @{
                            NSFontAttributeName : font,
                            NSForegroundColorAttributeName:color,
                            NSStrikethroughStyleAttributeName : @(NSUnderlineStyleSingle),
                            NSBaselineOffsetAttributeName : @(0)
                            };
    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:text attributes:attrDic];
    return attrStr;
}




/**
 富文本 【文本】
 @param text 字符串
 @return 属性文本
 */
+(NSMutableAttributedString *)zm_richText_text:(NSString *)text{
    return [[NSMutableAttributedString alloc] initWithString:text attributes:nil];
}

/**
 富文本
 @param Str 文本
 @param color 颜色
 @param font 字体大小
 */
+(NSMutableAttributedString *)zm_richText_text:(NSString *)Str color:(UIColor *)color font:(UIFont *)font{
    if (Str.length <= 0) {
        return nil;
    }
    NSMutableAttributedString *text = [ZMSpeedy zm_richText_text:Str];
    [text setYy_font:font];
    [text setYy_color:color];
    return text;
}

/**
 根据颜色生成imgage
 @param color 颜色
 */
+ (UIImage *)zm_createImageWithColor:(UIColor *)color
{
    //图片尺寸
    CGRect rect = CGRectMake(0, 0, 10, 10);
    //填充画笔
    UIGraphicsBeginImageContext(rect.size);
    //根据所传颜色绘制
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, color.CGColor);
    //显示区域
    CGContextFillRect(context, rect);
    // 得到图片信息
    UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
    //消除画笔
    UIGraphicsEndImageContext();
    return image;
}


/**
 富文本 【图文】

 @param str 字符串
 @param image 图标
 @param color 字体颜色
 @param font 字体大小
 @param position 图标的位置 1、图标在文本前面 2、图标在文本后面
 */
+(NSMutableAttributedString *)zm_richImgText_text:(NSString *)str image:(UIImage *)image textColor:(UIColor *)color font:(UIFont *)font imgPosition:(NSUInteger)position{
    NSMutableAttributedString *text = [NSMutableAttributedString new];
    {
        if (position == 1) {
            //图标在前
            //图标
            if (image) {
                NSMutableAttributedString *attachText = [ZMSpeedy zm_richYYLblImage_Img:image alignToFont:font verticalAlignment:YYTextVerticalAlignmentCenter];
                [text appendAttributedString:attachText];
            }

            //文本
            if (str) {
                NSString *title = [NSString stringWithFormat:@" %@",str];
                [text appendAttributedString:[ZMSpeedy zm_richText_text:title]];
            }
        }else if(position == 2){
            //图标在后

            //文本
            if (str) {
                NSString *title = [NSString stringWithFormat:@" %@",str];
                [text appendAttributedString:[ZMSpeedy zm_richText_text:title]];
            }

            //图标
            if (image) {
                NSMutableAttributedString *attachText = [ZMSpeedy zm_richYYLblImage_Img:image alignToFont:font verticalAlignment:YYTextVerticalAlignmentCenter];
                [text appendAttributedString:attachText];
            }
        }
        [text setYy_font:font];
        [text setYy_color:color];
    }

    return text;
}

/**
 富文本 【YYLabel图片】
 @param image 图片
 @param font 图片适应字体的大小
 @param alignment 垂直方向的位置
 @return 属性文本
 */
+(NSMutableAttributedString *)zm_richYYLblImage_Img:(UIImage *)image alignToFont:(UIFont *)font verticalAlignment:(YYTextVerticalAlignment)alignment{
    NSMutableAttributedString *attachment =
    [NSMutableAttributedString
     yy_attachmentStringWithContent:image
     contentMode:UIViewContentModeCenter
     attachmentSize:image.size
     alignToFont:font
     alignment:alignment];
    return attachment;
}


/**
 富文本 【UILabel图片】
 @param img 图片
 @param offset 偏移量
 */
+(NSMutableAttributedString *)zm_richLblImg_Img:(UIImage *)img offset:(CGPoint)offset{
    NSMutableAttributedString *matt = [NSMutableAttributedString new];
    NSTextAttachment *attch = [[NSTextAttachment alloc]init];
    attch.bounds = CGRectMake(offset.x,offset.y, img.size.width, img.size.height);
    attch.image = img;
    NSAttributedString *attStr = [NSAttributedString attributedStringWithAttachment:attch];
    [matt appendAttributedString:attStr];
    return matt;
}

#pragma mark-
#pragma mark- 表格刷新
//刷新某个组元
+(void)refreshCell:(UITableView *)tableView indexPath:(NSIndexPath *)indexPath{
    [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
}

//刷新某个单元格
+(void)refreshCell:(UITableView *)tableView row:(NSInteger)row section:(NSInteger)section{
    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:row inSection:section];
    [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
}
//刷新某组单元格
+(void)refreshSection:(UITableView *)tableView section:(NSInteger)section{
    //一个section刷新
    NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:section];
    [tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
}



#pragma mark-
#pragma mark- 判断
/** 判断是否【数字和字母组成】 */
+ (BOOL)validateArabNumOrLetter:(NSString *)str{
    NSString *passWordRegex = @"^[A-Za-z0-9]";
    NSPredicate *passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",passWordRegex];
    return [passWordPredicate evaluateWithObject:str];
}


/** 判断手机号码【只判断位数】 */
+ (BOOL)validateMoblieNum:(NSString *)mobileNum {
    NSString * phoneRegex = @"^(1[0-9])\\d{9}$";
    NSPredicate *num = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [num evaluateWithObject:mobileNum];
}
/**
 判断某个字符是否属于设置字符串
 
 @param str 字符
 @param toStr 字符串
 */
+ (BOOL)validateStr:(NSString*)str belongToStr:(NSString *)toStr{
    BOOL res = YES;
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:toStr];
    int i = 0;
    while (i < str.length) {
        NSString * string = [str substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0) {
            res = NO;
            break;
        }
        i++;
    }
    return res;
}

/**
 键盘验证是否是阿拉伯数字，是则显示不是就过滤
 @param number 判断的自渡船
 @return 返回是否是阿拉伯数字
 */
//在该方法中实现：-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
+ (BOOL)validateNumber:(NSString*)number {
    BOOL res = YES;
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    int i = 0;
    while (i < number.length) {
        NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0) {
            res = NO;
            break;
        }
        i++;
    }
    return res;
}

/**
 键盘验证是否是阿拉伯数字，是则显示不是就过滤
 @param number 判断的自渡船
 @return 返回是否是阿拉伯数字
 */
//在该方法中实现：-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
+ (BOOL)validateArabNumOrAddSymbol:(NSString*)number {
    BOOL res = YES;
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"+0123456789."];
    int i = 0;
    while (i < number.length) {
        NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0) {
            res = NO;
            break;
        }
        i++;
    }
    return res;
}

/**
 验证是否是身份证
 @param identityCard 身份证号码
 @return 返回是否是身份证号码
 */
+ (BOOL)validateIdentityCard:(NSString *)identityCard
{
    if (identityCard.length <= 0) {
        return NO;
    }
    NSString *regex = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    return [identityCardPredicate evaluateWithObject:identityCard];
}

/**
 * 银行卡号格式化和长度限制
 */
+(BOOL)bankCardNumLayoutAndLengthLimit:(UITextField *)textField inRange:(NSRange)range replacementString:(NSString *)string endBlock:(void (^)(NSString *newStr))compeleteBlock{
    //转局部变量
    NSString *text = textField.text;
    //判断是否为阿拉伯数字
    NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789\b"];
    //过滤空格
    string = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
    if ([string rangeOfCharacterFromSet:[characterSet invertedSet]].location != NSNotFound) {
        return NO;
    }
    //添加新字符
    text = [text stringByReplacingCharactersInRange:range withString:string];
    //过滤空格
    text = [text stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSString *newString = @"";
    while (text.length > 0) {
        NSString *subString = [text substringToIndex:MIN(text.length, 4)];
        newString = [newString stringByAppendingString:subString];
        if (subString.length == 4) {
            newString = [newString stringByAppendingString:@" "];
        }
        text = [text substringFromIndex:MIN(text.length, 4)];
    }
    newString = [newString stringByTrimmingCharactersInSet:[characterSet invertedSet]];
    // 限制长度
    if (newString.length >= 24) {
        return NO;
    }
    !compeleteBlock?:compeleteBlock(newString);
    [textField setText:newString];
    return NO;
}

/**
 * 身份证格式化和长度限制 无空格
 */
+(BOOL)idcardNumLengthLimit:(UITextField *)textField inRange:(NSRange)range replacementString:(NSString *)string endBlock:(void (^)(NSString *newStr))compeleteBlock {
    NSString *currentFieldText = textField.text;
    NSString *textFieldStr = @"";
    if ([string isEqualToString:@""]) {//退格键 如果不加这句 无法删除输入的内容
        if (currentFieldText.length > 0) {
            textFieldStr = [currentFieldText substringToIndex:currentFieldText.length - 1];
            textField.text = textFieldStr;
            !compeleteBlock?:compeleteBlock(textFieldStr);
            return NO;
        }
//        return YES;
    }
    
    if (textField.text.length >= 18) {//大于18位无法再继续输入
        return NO;
    }
    NSCharacterSet *_set = [NSCharacterSet characterSetWithCharactersInString:@"0123456789xX"];
    NSRange StrRange = [string rangeOfCharacterFromSet:_set];
    
    //判断输入的内容是否是规定的内容范围内 如果不是不做更改 如果是才输入
    if (StrRange.length == 0) {
        return NO;
    }else{
        textFieldStr = [NSString stringWithFormat:@"%@%@",currentFieldText,string];
//        return YES;
    }
    
    textField.text = textFieldStr;
    !compeleteBlock?:compeleteBlock(textFieldStr);
    
    return NO;
}

/**
 * 身份证格式化和长度限制 带空格
 */
+(BOOL)idCardLayoutAndLengthLimit:(UITextField *)textField replacementString:(NSString *)string{
    
    if (textField.text.length > 5)
    {
        if (string.length > 0 ) {
            if (textField.text.length == 6) {
                textField.text = [NSString stringWithFormat:@"%@ ", textField.text];
            }
        }
        // 四位加一个空格
        if ([string isEqualToString:@""]) { // 删除字符
            if ((textField.text.length - 9) % 5 == 0) {
                textField.text = [textField.text substringToIndex:textField.text.length - 1];
            }
            return YES;
        } else {
            if ((textField.text.length - 7) % 5 == 0 && textField.text.length != 6) {
                textField.text = [NSString stringWithFormat:@"%@ ", textField.text];
            }
        }
    }
    if (string.length == 0)
    {
        return YES;
    }
    if (textField.text.length > 21) {
        return NO;
    }
    return YES;
    
    
}

#pragma mark -
#pragma mark - 多线程
///主线程
+(void)GCDMainQueue:(void(^)(void))queue{
    dispatch_async(dispatch_get_main_queue(), ^{
        queue();
    });
}

///子线程
+(void)GCDGlobalQueue:(void(^)(void))queue{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        queue();
    });
}

///延迟线程
+(void)GCDAfter:(dispatch_time_t)time queueBlock:(void(^)(void))queue{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(time * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        queue();
    });
}


+(void)GCDMultiQueue:(void(^)(void))queue
{
    //1.获得全局的并发队列
    dispatch_queue_t qq = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    //2.添加任务到队列中，就可以执行任务
    //异步函数：具备开启新线程的能力
    dispatch_async(qq, ^{
        
        queue();
        
    });
}
+ (void)GCDInLineQueue:(void(^)(void))queue;
{
    //创建串行队列
    dispatch_queue_t  qq= dispatch_queue_create("wendingding", NULL);
    //第一个参数为串行队列的名称，是c语言的字符串
    //第二个参数为队列的属性，一般来说串行队列不需要赋值任何属性，所以通常传空值（NULL）
    dispatch_async(qq, ^{
        
        queue();
        
    });
}

#pragma mark-
#pragma mark- 系统小功能
/// 拨打电话
+(void)callWithPhone:(NSString *)phone{
    NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"telprompt://%@",phone];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
}

/**
 过滤字符串中的空白字符（\t \n \r）
 
 @param string 要过滤的字符串
 @return 过滤后的字符串
 */
+ (NSString *)filterBlankSpaceChatater:(NSString *)string
{
    string = [string stringByReplacingOccurrencesOfString:@"\r" withString:@""];
    string = [string stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    string = [string stringByReplacingOccurrencesOfString:@"\t" withString:@""];
    string = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
    return string;
}


/**
 过滤小数点【设置版本号使用】（.）
 @param string 要过滤的字符串
 @return 过滤后的字符串
 */
+ (NSString *)filterDecimalPointChatater:(NSString *)string{
    string = [string stringByReplacingOccurrencesOfString:@"." withString:@""];
    return string;
}

/// HTML适配图片文字
+ (NSString *)zm_adaptWebViewForHtml:(NSString *)htmlStr{
    NSString *bodyHtml = [NSString stringWithFormat:@"<html> \n"
     "<head> \n"
     "<meta charset=\"utf-8\">"
     "<meta id=\"viewport\" name=\"viewport\" content=\"width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=false\" />"
     "<style type=\"text/css\"> \n"
     "body {margin:18;font-size:14;color:0x666666}\n"
     "</style> \n"
     "</head> \n"
     "<body>"
     "<script type='text/javascript'>"
     "window.onload = function(){\n"
     "var $img = document.getElementsByTagName('img');\n"
     "for(var p in  $img){\n"
     " $img[p].style.width = '100%%';\n"
     "$img[p].style.height ='auto'\n"
     "}\n"
     "}"
     
     "</script>%@"
     "</body>"
    "<script type='text/javascript'>\
    const setMedia = function(video) {\
    var src = video.src;\
    src += '?x-oss-process=video/snapshot,t_0,f_jpg,m_fast';\
    video.setAttribute('poster', src);\
    video.setAttribute('style','background-color:black;');\
    };\
    let videos = document.querySelectorAll('video');\
    videos.forEach((video) => {\
    setMedia(video)\
    });\
    </script>\n"
     "</html>",htmlStr];
    
    /// 禁止全屏播放
    CGFloat phoneVersion = [[[UIDevice currentDevice] systemVersion] floatValue];
    if (phoneVersion >= 10.0) {
        bodyHtml = [bodyHtml stringByReplacingOccurrencesOfString:@"<video" withString:@"<video playsinline"];
    }else {
        bodyHtml = [bodyHtml stringByReplacingOccurrencesOfString:@"<video" withString:@"<video webkit-playsinline"];
    }
    
    return bodyHtml;
    
}


// 根据图片url获取图片尺寸
+(CGSize)getImageSizeWithURL:(id)imageURL{
    NSURL* URL = nil;
    if([imageURL isKindOfClass:[NSURL class]]){
        URL = imageURL;
    }
    if([imageURL isKindOfClass:[NSString class]]){
        URL = [NSURL URLWithString:imageURL];
    }
    if(URL == nil)
        return CGSizeZero; // url不正确返回CGSizeZero
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:URL];
    request.timeoutInterval = 0.5;
    NSString* pathExtendsion = [URL.pathExtension lowercaseString];
    CGSize size = CGSizeZero;
    if([pathExtendsion isEqualToString:@"png"]){
        size = [self getPNGImageSizeWithRequest:request];
    }
    else if([pathExtendsion isEqual:@"gif"])
    {
        size = [self getGIFImageSizeWithRequest:request];
    }
    else{
        size = [self getJPGImageSizeWithRequest:request];
    }
    if(CGSizeEqualToSize(CGSizeZero, size)) // 如果获取文件头信息失败,发送异步请求请求原图
    {
        NSData* data = [NSURLConnection sendSynchronousRequest:[NSURLRequest requestWithURL:URL] returningResponse:nil error:nil];
        UIImage* image = [UIImage imageWithData:data];
        if(image)
        {
            size = image.size;
        }
    }
    return size;
}
// 获取PNG图片的大小
+(CGSize)getPNGImageSizeWithRequest:(NSMutableURLRequest*)request
{
    [request setValue:@"bytes=16-23" forHTTPHeaderField:@"Range"];
    NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    if(data.length == 8)
    {
        int w1 = 0, w2 = 0, w3 = 0, w4 = 0;
        [data getBytes:&w1 range:NSMakeRange(0, 1)];
        [data getBytes:&w2 range:NSMakeRange(1, 1)];
        [data getBytes:&w3 range:NSMakeRange(2, 1)];
        [data getBytes:&w4 range:NSMakeRange(3, 1)];
        int w = (w1 << 24) + (w2 << 16) + (w3 << 8) + w4;
        int h1 = 0, h2 = 0, h3 = 0, h4 = 0;
        [data getBytes:&h1 range:NSMakeRange(4, 1)];
        [data getBytes:&h2 range:NSMakeRange(5, 1)];
        [data getBytes:&h3 range:NSMakeRange(6, 1)];
        [data getBytes:&h4 range:NSMakeRange(7, 1)];
        int h = (h1 << 24) + (h2 << 16) + (h3 << 8) + h4;
        return CGSizeMake(w, h);
    }
    return CGSizeZero;
}
// 获取gif图片的大小
+(CGSize)getGIFImageSizeWithRequest:(NSMutableURLRequest*)request
{
    [request setValue:@"bytes=6-9" forHTTPHeaderField:@"Range"];
    NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    if(data.length == 4)
    {
        short w1 = 0, w2 = 0;
        [data getBytes:&w1 range:NSMakeRange(0, 1)];
        [data getBytes:&w2 range:NSMakeRange(1, 1)];
        short w = w1 + (w2 << 8);
        short h1 = 0, h2 = 0;
        [data getBytes:&h1 range:NSMakeRange(2, 1)];
        [data getBytes:&h2 range:NSMakeRange(3, 1)];
        short h = h1 + (h2 << 8);
        return CGSizeMake(w, h);
    }
    return CGSizeZero;
}
// 获取jpg图片的大小
+(CGSize)getJPGImageSizeWithRequest:(NSMutableURLRequest*)request
{
    [request setValue:@"bytes=0-209" forHTTPHeaderField:@"Range"];
    NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    if ([data length] <= 0x58) {
        return CGSizeZero;
    }
    if ([data length] < 210) {// 肯定只有一个DQT字段
        short w1 = 0, w2 = 0;
        [data getBytes:&w1 range:NSMakeRange(0x60, 0x1)];
        [data getBytes:&w2 range:NSMakeRange(0x61, 0x1)];
        short w = (w1 << 8) + w2;
        short h1 = 0, h2 = 0;
        [data getBytes:&h1 range:NSMakeRange(0x5e, 0x1)];
        [data getBytes:&h2 range:NSMakeRange(0x5f, 0x1)];
        short h = (h1 << 8) + h2;
        return CGSizeMake(w, h);
    } else {
        short word = 0x0;
        [data getBytes:&word range:NSMakeRange(0x15, 0x1)];
        if (word == 0xdb) {
            [data getBytes:&word range:NSMakeRange(0x5a, 0x1)];
            if (word == 0xdb) {// 两个DQT字段
                short w1 = 0, w2 = 0;
                [data getBytes:&w1 range:NSMakeRange(0xa5, 0x1)];
                [data getBytes:&w2 range:NSMakeRange(0xa6, 0x1)];
                short w = (w1 << 8) + w2;
                short h1 = 0, h2 = 0;
                [data getBytes:&h1 range:NSMakeRange(0xa3, 0x1)];
                [data getBytes:&h2 range:NSMakeRange(0xa4, 0x1)];
                short h = (h1 << 8) + h2;
                return CGSizeMake(w, h);
            } else {// 一个DQT字段
                short w1 = 0, w2 = 0;
                [data getBytes:&w1 range:NSMakeRange(0x60, 0x1)];
                [data getBytes:&w2 range:NSMakeRange(0x61, 0x1)];
                short w = (w1 << 8) + w2;
                short h1 = 0, h2 = 0;
                [data getBytes:&h1 range:NSMakeRange(0x5e, 0x1)];
                [data getBytes:&h2 range:NSMakeRange(0x5f, 0x1)];
                short h = (h1 << 8) + h2;
                return CGSizeMake(w, h);
            }
        } else {
            return CGSizeZero;
        }
    }
}

/// 获取拼音首字母(传入汉字字符串, 返回大写拼音首字母)
+ (NSString *)zm_firstCharactor:(NSString *)aString{
    //转成了可变字符串
    NSMutableString *str = [NSMutableString stringWithString:aString];
    //先转换为带声调的拼音
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformMandarinLatin,NO);
    //再转换为不带声调的拼音
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformStripDiacritics,NO);
    //转化为大写拼音
    NSString *pinYin = [str capitalizedString];
    //获取并返回首字母
    return [pinYin substringToIndex:1];
}

#pragma mark - 自适应字体
/**
 根据字符串高度返回宽度
 
 @param font 字号
 @param text 输入的字符串
 @param height 要的高度
 @return 返回的宽度
 */
+(CGFloat)returnStringWidthWithFont:(UIFont * )font Text:(NSString *)text With:(CGFloat)height
{
    CGSize maxSize = CGSizeMake(MAXFLOAT,height);
    CGSize textRealSize = [text boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font} context:nil].size;
    return textRealSize.width;
}

/**
 根据字符串宽度返回高度(CGFloat)
 
 @param font 字号
 @param text 输入的字符串
 @param width 要的宽度
 @return 返回的高度
 */
+ (CGFloat )returnStringHeightWithFont:(UIFont * )font Text:(NSString *)text MaxWidth:(CGFloat)width{
    //iOS 7以上用下面的方法
    NSDictionary *attributes = @{NSFontAttributeName:font};
    
    CGSize size = [text boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attributes context:nil].size;
    return size.height;
}

/**
 给一个view画虚线
 
 @param view 父view
 */
+ (void)drawDottedLine:(UIView *)view color:(UIColor *)color {
    CAShapeLayer *border = [CAShapeLayer layer];
    border.strokeColor = color.CGColor;
    border.fillColor = nil;
    border.path = [UIBezierPath bezierPathWithRect:view.bounds].CGPath;
    border.frame = view.bounds;
    border.lineWidth = 1.f;
    border.lineCap = @"square";
    border.lineDashPattern = @[@6, @4];
    [view.layer addSublayer:border];
}


/**
 添加四边阴影效果
 
 @param theView theView description
 @param theColor theColor description
 */
+ (void)addShadowToView:(UIView *)theView withColor:(UIColor *)theColor {
    // 阴影颜色
    theView.layer.shadowColor = theColor.CGColor;
    // 阴影偏移，默认(0, -3)
    theView.layer.shadowOffset = CGSizeMake(0,-3);
    // 阴影透明度，默认0
    theView.layer.shadowOpacity = 0.5;
    // 阴影半径，默认3
    theView.layer.shadowRadius = 5;
}

// 判断字符串的字节长度
+(NSUInteger)zm_asciiLengthOfString: (NSString *) text {
    NSUInteger asciiLength = 0;
    for (NSUInteger i = 0; i < text.length; i++) {
        unichar uc = [text characterAtIndex: i];
        asciiLength += isascii(uc) ? 1 : 2;
    }
    return asciiLength;
}



/**
 转换HTML文本
 */
+ (NSAttributedString *)converteAttributedStringWithStr:(NSString *)str {
    
    NSAttributedString *attributedString = [[NSAttributedString alloc] initWithData:[str dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
    return attributedString;
}

/**
 秒数转换成小时和分钟用于详情页的倒计时
 
 @param seconds 秒数
 @return 转换成小时、分钟
 */
+ (NSString *)convertedHourAndMinutesAndSecondsWithSeconds:(NSInteger)seconds {
    NSInteger hour = seconds/3600;
    NSInteger minutes = (seconds - hour*3600)/60;
    NSInteger s = seconds%60;
    return [NSString stringWithFormat:@"%02ld:%02ld:%02ld",hour,minutes,s];
}

@end
